// composables/usePagination.js
import { ref, reactive } from 'vue'
/**
 * 
 * @param {*} apiFn  请求数据
 * @param {*} initialParams  搜索参数
 * @returns 
 */
export function usePagination(apiFn, initialParams = {}) {
  // 分页数据
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  const data = ref([])
  const loading = ref(false)

  // 搜索参数（可扩展）
  const queryParams = reactive({ ...initialParams })

  // 获取数据
  const fetchData = async () => {
    console.log('fetchData')
    loading.value = true
    try {
      const params = {
        page: currentPage.value,
        limit: pageSize.value,
        ...queryParams
      }
      console.log('params', params)

      // const res = await apiFn(params)
      const res = {
        data:{
          list:[
            {
              id:1,
              name:'张三',
              email:'111@qq.com'
            },
            {
              id:2,
              name:'李四',
              email:'222@qq.com'
            },
            {
              id:3,
              name:'王二',
              email:'333@qq.com'
            }
          ],
          total:10
        },
      }
      // 假设后端返回 { data: { list, total } }
      if (res?.data) {
        data.value = res.data.list || res.data
        total.value = res.data.total || res.total || 0
      }
    } catch (error) {
      console.error('请求失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 改变页码
  const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchData()
  }

  // 改变每页数量
  const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1 // 重置到第一页
    fetchData()
  }

  // 搜索（可带条件）
  const handleSearch = () => {
    currentPage.value = 1
    fetchData()
  }

  // 重置搜索
  const reset = () => {
    currentPage.value = 1
    Object.keys(queryParams).forEach((key) => {
      queryParams[key] = initialParams[key] || null
    })
    fetchData()
  }

  // 初始调用
  fetchData()

  return {
    // 数据
    data,
    total,
    currentPage,
    pageSize,
    loading,
    queryParams,

    // 方法
    fetchData,
    handleCurrentChange,
    handleSizeChange,
    handleSearch,
    reset
  }
}
